import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import { getCookie } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: 'https://h5-api.juanzhijia.com/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1800000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token --['X-Token'] as a custom key.
      // please modify it according to the actual situation.
      config.headers['token'] = store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code.
   */
  response => {
    const res = response.data
    // if the custom code is not 200, it is judged as an error.
    if(res.code === 200){

      // let getTimestamp = new Date().getTime();
      // console.log(getTimestamp,'getTimestamp')
      return res

    }
    if (res.code !== 200) {
      console.log(response.status,'-------失效状态')
      if((response.status != 50008) && (response.status != 50010) && (response.status != 50011) && (response.status != 50012) && (response.status != 50013) && (response.status != 50014)){
        Message({
          message: res.message || 'error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      
      return Promise.reject(res.message || 'error')
    } else {
      return res
    }
  },
  error => {
    if(error.response.status === 50008 || error.response.status === 50010 || error.response.status === 50011 || error.response.status === 50012 || error.response.status === 50013 || error.response.status === 50014){
      // to re-login
      MessageBox.confirm('登录已失效, 请重新登录', '提示', {
        confirmButtonText: '去登录',
        // cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }else{
      return Promise.reject(error.response.data)
    }
    // console.log('err' + error.response.data.message) // for debug
    // Message({
    //   message: error.response.data.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
  }
)

export default service
